package subumbo.leg.service
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import org.osflash.signals.Signal;
	import org.osmf.utils.URL;
	import org.robotlegs.mvcs.Actor;
	
	/**
	 * Base class for services for URL Requests. It encapsulates a flash URLLoader instance. This service dispatches a loaded Signal. 
	 * @author pwolleb
	 * 
	 */	
	
	public class URLService extends Actor implements IService
	{
		protected var _request:URLRequest = new URLRequest();
		public var loadedSignal:Signal = new Signal();
		public var progressSignal:Signal = new Signal(Number);

		public function send():void {
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, onResult, false, 0 ,true);
			loader.addEventListener(ProgressEvent.PROGRESS, onProgress, false, 0 ,true);
			loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError, false, 0 ,true);
			loader.load(_request);
		}
		
		protected function onResult(e:Event):void {
			e.stopImmediatePropagation();
			var loader:URLLoader = URLLoader(e.currentTarget);
			loader.removeEventListener(Event.COMPLETE, onResult);
			loader.removeEventListener(ProgressEvent.PROGRESS, onProgress);
			loader.removeEventListener(Event.COMPLETE, onResult);
			loadedSignal.dispatch();
		}
				
		protected function onProgress(e:ProgressEvent):void {
			progressSignal.dispatch(e.bytesTotal / e.bytesLoaded * 100);
		}
		
		protected function onIOError(e:IOErrorEvent):void {
			trace("URLService::onIOError \n URL: " + e.text );;
		}
		
		public function set request(val:URLRequest):void {
			_request = val;
		}
		
		public function get request():URLRequest {
			return _request;
		}
	}
}